/*
 * GuudLog.cpp
 *
 *  Created on: 2013-1-19
 *      Author: heqiu
 */

#include "GuudLog.h"

namespace guud {
GuudLog::GuudLog() {
	m_filename = "./log.txt";
}
void GuudLog::setLogName(const char * filename) {
	m_filename = filename;
}
void GuudLog::log(const char * csformat, ...) {
	va_list ap;
	va_start(ap, csformat);
	log(csformat, ap);
	va_end(ap);
}
void GuudLog::log(const char * csformat, va_list &ap) {
	char logBuf[1024 * 4];
	int fd = -1;
	fd = open(m_filename.c_str(), O_RDWR | O_CREAT | O_APPEND, 0644);
	if (fd < 0) {
		return;
	}
	{
		time_t timep;
		struct tm *p;
		time(&timep);
		p = localtime(&timep);
		int len = snprintf(logBuf, sizeof(logBuf) - 1,
				"[%02d-%02d %02d:%02d:%02d]", (1 + p->tm_mon), p->tm_mday,
				p->tm_hour, p->tm_min, p->tm_sec);
		if (len >= 0) {
			int iRet = write(fd, logBuf, len);
			if (iRet < 0) {
				return;
			}
		}
	}
	//只判断>0有时会返回错误,len返回值会大于bufsize,是该函数一个bug,与函数说明不符合
	int len = vsnprintf(logBuf, sizeof(logBuf) - 2, csformat, ap);
	if (len >= 0 && len < (int) (sizeof(logBuf) - 1)) {
		logBuf[len] = '\n';
		len++;
		int iRet = write(fd, logBuf, len);
		if (iRet < 0) {
			return;
		}
	} else {
		//如果len>0,则返回需要的空间大小
		//如果len=-1,则未知空间大小,与具体环境有关
		char *tmpBuf;
		int bufSize = 1024 * 10;

		while (true) {
			tmpBuf = new char[bufSize];
			if (tmpBuf == NULL) {
				return;
			}
			len = vsnprintf(tmpBuf, bufSize - 1, csformat, ap);
			if (len >= 0 && len < bufSize - 1) {
				break;
			} else {
				bufSize *= 2;
				delete[] tmpBuf;
				continue;
			}
			break;
		}
		tmpBuf[len] = '\n';
		int iRet = write(fd, tmpBuf, len);
		if (iRet < 0) {
			return;
		}
		delete[] tmpBuf;
	}
	close(fd);
}
}

